using System;
using System.Collections.Generic;
using UnityEngine;
using com.ljsd.jieling.protocols;

public class MailManager : MonoBehaviour
{
    public static MailManager Instance;
    
    [SerializeField]
    private List<Mail> mailList = new List<Mail>();
    
    public List<Mail> MailList => mailList;
    
    public Action OnMailDataUpdated;
    
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    public void InitMailDataList(GetAllMailInfoResponse data)
    {
        if (data != null && data.mialList != null)
        {
            mailList.Clear();
            mailList.AddRange(data.mialList);
            
            Debug.Log($"初始化邮件数据成功，共 {mailList.Count} 封邮件");
            
            // 打印邮件信息
            foreach (var mail in mailList)
            {
                Debug.Log($"邮件ID: {mail.mailId}, 标题: {mail.head}, 状态: {mail.state}, 发送者: {mail.sendName}");
            }
            
            OnMailDataUpdated?.Invoke();
        }
    }
    
    public void RequestMailList()
    {
        Debug.Log("开始请求邮件列表...");
        NetManager.GetAllMailData(() => {
            Debug.Log("邮件列表请求完成");
        });
    }
    
    //public Mail GetMailById(string mailId)
    //{
    //    return mailList.Find(mail => mail.mailId == mailId);
    //}
    
    //public List<Mail> GetUnreadMails()
    //{
    //    return mailList.FindAll(mail => mail.state == 0); // 0表示未读
    //}
    
    //public List<Mail> GetMailsWithAttachments()
    //{
    //    return mailList.FindAll(mail => !string.IsNullOrEmpty(mail.mailItem));
    //}
    
    public void PrintAllMails()
    {
        Debug.Log("=== 邮件列表 ===");
        foreach (var mail in mailList)
        {
            Debug.Log($"ID: {mail.mailId}");
            Debug.Log($"标题: {mail.head}");
            Debug.Log($"内容: {mail.content}");
            Debug.Log($"状态: {(mail.state == 0 ? "未读" : "已读")}");
            Debug.Log($"发送者: {mail.sendName}");
            Debug.Log($"发送时间: {GetDateTimeFromTimestamp(mail.sendTime)}");
            Debug.Log($"有效期: {GetDateTimeFromTimestamp(mail.effectiveTime)}");
            if (!string.IsNullOrEmpty(mail.mailItem))
            {
                Debug.Log($"附件: {mail.mailItem}");
            }
            Debug.Log("-------------------");
        }
    }
    
    private DateTime GetDateTimeFromTimestamp(int timestamp)
    {
        DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        return dateTime.AddSeconds(timestamp).ToLocalTime();
    }

   
}